﻿using System.Collections.Generic;
using System.Diagnostics;
using System;
using System.Management;
using System.Linq;
using System.IO;

namespace ApplicationManager.Services
{
    public class ProcessHelper
    {


        public static List<int> GetChildProcessesCsv(int parentProcessId)
        {
            var childProcesses = new List<int>();

            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "wmic",
                        Arguments = $"process where \"ParentProcessId={parentProcessId}\" get ProcessId,Name /format:csv",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = System.Text.Encoding.UTF8
                    }
                };

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                // 解析CSV格式输出
                var list = ParseCsvOutput(output);
                childProcesses.AddRange(list);
                foreach (var subid in list)
                {
                    childProcesses.AddRange(GetChildProcessesCsv(subid));
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行WMIC CSV命令失败: {ex.Message}");
            }

            return childProcesses;
        }

        private static List<int> ParseCsvOutput(string output)
        {
            var processes = new List<int>();

            var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string line in lines)
            {
                string trimmedLine = line.Trim();

                // 跳过标题行
                if (trimmedLine.StartsWith("Node,") || string.IsNullOrEmpty(trimmedLine))
                {
                    continue;
                }

                // 解析CSV行：Node,ProcessId,Name
                var parts = trimmedLine.Split(',');
                if (parts.Length >= 3)
                {
                    if (int.TryParse(parts[2], out int processId))
                    {
                        processes.Add(processId);
                    }
                }
            }

            return processes;
        }


        public class ProcessInfo
        {
            public int ProcessId { get; set; }
            public string CommandLine { get; set; }
        }



     

        /// <summary>
        /// 使用Process类获取进程信息（备选方案，但命令行信息可能不完整）
        /// </summary>
        public static List<ProcessInfo> GetProcessesAlternative(string processName)
        {
            var processList = new List<ProcessInfo>();

            try
            {
                var processes = Process.GetProcessesByName(processName.Replace(".exe", ""));

                foreach (var process in processes)
                {
                    var processInfo = new ProcessInfo
                    {
                        ProcessId = process.Id,
                        CommandLine = GetProcessCommandLine(process.Id) // 需要额外的WMI查询获取完整命令行
                    };

                    processList.Add(processInfo);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取进程信息时出错: {ex.Message}");
            }

            return processList;
        }

        /// <summary>
        /// 通过进程ID获取命令行（辅助方法）
        /// </summary>
        private static string GetProcessCommandLine(int  processId)
        {
            try
            {
                string query = $" process where \"ProcessId={processId}\" get CommandLine";

                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "wmic",
                        Arguments = query,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = System.Text.Encoding.UTF8
                    }
                };

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                output=output.Replace("CommandLine", "");
                return output;
            }
            catch
            {
                return string.Empty;
            }

           
        }



    }
}
